package org.openfans.feed;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openfans.domain.Fans;
import org.openfans.domain.Feed;
import org.openfans.domain.FeedItem;
import org.openfans.persistence.Fetcher;
import org.openfans.persistence.Persistence;

public class FeedManager {
	private static final Log logger = LogFactory.getLog(FeedManager.class);

	private FeedRetriever feedRetriever;

	private Fetcher fetcher;

	private Persistence persistence;

	public void addNewFeed(Fans fans, String url) throws FeedRetrieveException {
		Feed feed = feedRetriever.getFeedInfoFromUrl(url);
		feed.setFans(fans);
		// 设置一个较早的最后更新时间2000年一月一号，防止出nullPointException
		feed.setLastDate(new Date(100, 0, 1));
		persistence.save(feed);
	}

	/**
	 * 更新所有feed的类，在双cpu的服务器下会出现2个线程同时启动的问题 方法synchronized无效，使用
	 * 
	 */
	public synchronized void refreshAllFeeds() {

		List<Feed> feeds = fetcher.getAllFeeds();
		if (logger.isInfoEnabled()) {
			logger.info("refreshAllFeeds() - start fresh feeds，feed count:"
					+ feeds.size());
		}
		for (Feed feed : feeds) {
			try {
				refreshFeed(feed);
			} catch (Throwable e) {
				// 忽略，继续下面的更新
				//这里使用Throwable,防止因为某种未知错误发生,导致整体失败
			}
		}
		if (logger.isInfoEnabled()) {
			logger.info("refreshAllFeeds() - end");
		}
	}
	
	

	/**
	 * 功能说明：更新一个feed，把新的文章读入<br>
	 * 创建者：张俊<br>
	 * 创建时间：2006-5-31<br>
	 * 
	 * @param feed
	 * @throws FeedRetrieveException
	 */
	public void refreshFeed(Feed feed) throws FeedRetrieveException {
		if (logger.isInfoEnabled()) {
			logger.info("refreshFeed(Feed) - refresh feed url:"
					+ feed.getFeedUrl());
		}
		try {
			List<FeedItem> items = feedRetriever.getNewFeedItems(feed);
			// 拿到上次最后一个item的时间
			Date date = feed.getLastDate();
			for (FeedItem fi : items) {
				saveFeedItem(fi);
				// 取得最后的更新时间
				if (date.before(fi.getPublishDate())) {
					date = fi.getPublishDate();
				}
				feed.setLastDate(date);
				persistence.save(feed);
			}
		} catch (Exception e) {
			logger.error("更新feed--" + feed.getFeedUrl() + " 时出错", e);
			throw new FeedRetrieveException("");
		}

	}

	/**
	 * 功能说明：将blog中新的文章保存<br>
	 * 创建者：张俊<br>
	 * 创建时间：2006-5-31<br>
	 * 
	 * @param fi
	 */
	private void saveFeedItem(FeedItem fi) {
		persistence.save(fi);
	}

	public void setFeedRetriever(FeedRetriever feedRetriever) {
		this.feedRetriever = feedRetriever;
	}

	public void setFetcher(Fetcher fetcher) {
		this.fetcher = fetcher;
	}

	public void setPersistence(Persistence persistence) {
		this.persistence = persistence;
	}

}
